package com.example.chapter8iservice;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import java.io.IOException;

public class MyService extends Service {
    private String TAG = "TAG";
    public class MusicBinder extends Binder {
        MyService getService(){
            return MyService.this;
        }
    }


    private  IBinder binder = new MusicBinder();

    MediaPlayer mediaPlayer;

    public MyService() {
    }
    public void play(){
        mediaPlayer.start();
    }
    public void stop(){
        mediaPlayer.stop();
        try {
            mediaPlayer.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void pause(){
        mediaPlayer.pause();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.e(TAG, "onCreate: MyService");
        mediaPlayer = MediaPlayer.create(getApplicationContext(),R.raw.music01);
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        mediaPlayer.start();
        Log.e(TAG, "onBind: mediaplayer.start");
        return binder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.e(TAG, "onUnbind: ");
        return super.onUnbind(intent);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG, "onStartCommand: ");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mediaPlayer.stop();
        mediaPlayer.release();
        Log.e(TAG, "onDestroy: 音乐停止" );
    }
}